$(function () {
    var $select = $('.btn-select'),
        $combine = $('.btn-combine'),
        $canSend = $('.can-send-total'),
        $SendNumber = $('.send-total'),
        $submitSend = $('.btn-submit-send'),
        strSelectHtml = $('#form-select').html(),
        strSummaryHtml = $('#template-summary').html(),
        strCombineHtml = $('#form-combine').html(),
        strOrderItemHtml = $('#template-order-item').html(),
        strPurchaseBillItemHtml = $('#template-purchase-bill').html(),
        _search = parseSearch(), selected = {};
    var config = {
        getRelatedOrder: '/order/queryByClienteleIdAndOfferId',
        getPurchaseOrderBill: '/purchaseOrderBill/query?keyword=send&size=25&goodsId=',
        create_labing_bill: '/ladingBill/create',
        create_labing_bill_unpaied: '/ladingBill/createUnPaied',
        query_store: '/store/queryPinyin?size=300',//分页查询URL,

        detail: '/order/get?id=' + _search.id
    }, orders = {}, bills = {};
    var selected_ = {};

    function initNumberPage(item, isremove) {
        if (isremove) {
            if (orders[item.id]) {
                delete orders[item.id];
            }
        } else {
            orders[item.id] = item;
        }
        var total = 0;
        Object.keys(orders).map(function (key) {
            total = floatTool.add(total, floatTool.subtract(orders[key].number, orders[key].deliverNumber));
        });
        $canSend.html(total);
        initSendNumberThisTime();
    }

    function initSendNumberThisTime() {
        onInput($('.send-order').find('input'), function () {
            calculate();
        });
        calculate();
    }

    /**
     * @date 2017-06-06
     * @desc
     */
    function calculate() {
        var total = 0;
        $('.send-order').find('input[name=orderNumbers]').each(function () {
            total = floatTool.add(total, parseFloat($(this).val()));
        });
        $SendNumber.html(total);
        return total;
    }

    function initEvent() {
        onInput($('.send-order input[name=orderNumbers]'), function () {
            if (parseFloat($(this).val()) > parseFloat($(this).attr('max'))) {
                $(this).val($(this).attr('max'))
            }
            var data = $(this).closest('tr').data('json');
            data.sendNum = parseFloat($(this).val());
            $(this).closest('tr').data('json');

        });
    }

    /***
     * 初始化批号数量
     */
    function initBatchNum() {
        var total = calculate();
        $('body .parchase-bill [name=billNumbers]').each(function (index, item) {
            var $max = parseFloat($(this).attr('max'));
            if (total > 0) {
                if (total > $max) {
                    $(this).val($max).siblings('.billNumbers').html($max);
                    total = floatTool.subtract(total, $max);
                } else {
                    $(this).val(total).siblings('.billNumbers').html(total);
                    total = 0;
                }
            }
        })
    }

    if (parseSearch().type == 2 || parseSearch().type == 1) {
        $('.type-order .td-label:first-child').html('转货公司：');
        $('.type-order .td-label:nth-child(3)').html('免费仓储期：');
        $('.nav-pills li:nth-child(' + (1 + parseInt(parseSearch().type)) + ')').addClass('active').siblings('li').removeClass('active');
        $('.type-order [name=type]').val(parseSearch().type);
    }
    $.get(config.detail, function (res) {
        if (res.code == 200) {
            res.data.canSendNum = floatTool.subtract(res.data.number, res.data.deliverNumber);
            res.data.sendNum = res.data.canSendNum; // 订单本次发货数量
            res.data.createAt = formatTime(res.data.createAt);
            res.data.must = 'true';
            $('.panel-body ').prepend(ejs.render(strSummaryHtml, res.data));
            var $tr = $(ejs.render(strOrderItemHtml, res.data)).find('td:last-child').html('').end();
            $tr.data('json', res.data);
            $tr.insertBefore('.send-order tr:last-child');
            focusEvent();
            initEvent();

            onInput($('[name=orderNumbers]'), function () {
                if (parseFloat($(this).val()) > parseFloat($(this).attr('max'))) {
                    $(this).val($(this).attr('max'));
                }
                initSendNumberThisTime();
                initBatchNum();
            });
            initNumberPage(res.data);
            initSendNumberThisTime();
            onClick($('.nav-pills li'), function () {
                if ($(this).hasClass('active')) {
                    return;
                }
                window.location = './send.html?id=' + parseSearch().id + '&type=' + $(this).index();
            });
            $combine.data('json', res.data);
            function initTips(total, total_) {
                if (!$('.modal-header .modal-title .pull-right').length) {
                    $('.modal-header .modal-title').append('<span class="pull-right" style="margin-right: 150px;">本次合计发货数量：' + total + ' 吨，已选批号库存：' + total_ + ' 吨</span>');
                } else {
                    var total_1 = {}, total1 = calculate();
                    $('.send-order').find('tr').each(function (ind, item) {
                        var $json = $(item).data('json');
                        if ($json) {
                            total_1[$json.id] = $json;
                        }
                    });
                    total_ = 0, matchNum = 0;
                    $('.modal-body .table tr').map(function (ind, item) {
                        var $input = $(item).find('td:first-child input');
                        if ($input.length) {
                            if ($input.is(':checked')) {
                                var $json = $input.data('json');
                                var inputVal = $input.closest('tr').find('[type=text]').val();
                                if (parseFloat(inputVal) !== NaN) {
                                    matchNum = floatTool.add(matchNum, parseFloat(inputVal));
                                }
                                if ($json) {
                                    var t = $json.numberReceive > 0 ? floatTool.subtract(floatTool.subtract($json.numberReceive, $json.numberSended), $json.numberSending) : (
                                        $json.type == 0 ? $json.number : (floatTool.subtract(floatTool.subtract($json.number, $json.numberSended), $json.numberSending)));
                                    total_ = floatTool.add(total_, t);
                                }
                            }
                        }
                    });
                    $('.modal-header .modal-title .pull-right').html('提单数量：' + total1 + ' 吨，已选批号数量：' + total_ + ' 吨,批号匹配数量：' + matchNum + '吨')
                }
            }

            function sortSelected(selects) {
                var selected_1 = {};
                _.sortBy(_.values(selects), 'sort').map(function (item, index) {
                    item.sort = index;
                    selected_1[item.id] = item;
                });
                return selected_1;
            }

            /**
             *  获取批号可发货数量
             * @param $json
             * @returns {number}
             */
            function getCanSend($json) {
                var tmp_ = 0;
                if ($json.type == 1 && $json.numberReceive > 0) { // 已入库转货权收货单
                    var tmp = floatTool.subtract($json.numberReceive, $json.numberSended);//　扣减批号已发货数量
                    tmp_ = floatTool.subtract(tmp, $json.numberSending);　// 扣减批号发货中数量
                } else if ($json.type == 2) { // 批号未入库
                    var tmp = floatTool.subtract($json.number, $json.numberSended);//　扣减批号已发货数量
                    tmp_ = floatTool.subtract(tmp, $json.numberSending);　// 扣减批号发货中数量
                } else { // 批号等于
                    tmp_ = $json.number;
                }
                return tmp_;
            }

            function getSelectedBatch(id, $this) { // 批号先选择先匹配
                selected_ = selected_ || {};
                var total = 0, //
                    total_ = calculate(); // 合计需匹配数量
                var restNumForMatch = total_;
                if ($this) {
                    var $json = $($this).data('json');
                    //
                    if ($($this).is(':checked')) {
                        selected_ = sortSelected(selected_);
                        $json.sort = Object.keys(selected_).length + 1;
                        selected_[$json.id] = $json;

                    } else {
                        delete  selected_[$json.id];
                    }
                }


                var st = _.uniq(_.pluck(_.values(selected_), 'storeId'));
                if (st.length > 1) fnFail("所选批号和已选批号仓库地不一致！");
                // 匹配订单
                _.sortBy(_.values(selected_), 'sort').map(function (item) { //
                    var $this_ = $('[name=selected' + item.id + ']');
                    var $json = $this_.data('json'),
                        tmp_ = getCanSend($json); // 批号可使用数量 //

                    if (true) {
                        var inputVal = $this_.closest('tr').find('[type=text]').val();
                        if (restNumForMatch == 0) {
                            return $this_.closest('tr').find('[type=text]').val(0)
                        }
                        if (parseFloat(inputVal) == NaN) { //  非数字 ，计算
                            inputVal = tmp_;
                        } else {
                            inputVal = parseFloat(inputVal);
                            if (inputVal > tmp_ || inputVal == 0) {
                                inputVal = tmp_;
                            }
                        }
                        if (restNumForMatch >= inputVal) {
                            restNumForMatch = floatTool.subtract(restNumForMatch, inputVal);//
                        } else {
                            inputVal = restNumForMatch;
                            restNumForMatch = 0;
                        }
                        return $this_.closest('tr').find('[type=text]').val(inputVal);

                    }
                    /**
                     * @deprecated 3期后废弃此后代码
                     */
                    var totalTmp = floatTool.add(total, tmp_); // dangqian
                    var $input = $this_.closest('tr').find('input[type=text]');
                    var numberInput = parseFloat($input.val() || 0);
                    if (numberInput > 0) {
                        var totalTmp_ = floatTool.add(total, numberInput);
                        if (totalTmp_ > total_) {
                            $input.val(floatTool.subtract(total_, numberInput));
                            // total_ = 0;
                        } else {
                            // total_ = floatTool.subtract(total_, numberInput);
                        }
                    } else if (totalTmp == total_) {
                        $input.val(floatTool.subtract(total_, total))
                    } else if (totalTmp > total_) {
                        if (total_ >= total) {
                            $this_.closest('tr').find('input[type=text]').val(floatTool.subtract(total_, total))
                        } else {
                            // $this_.attr('checked', false).prop('checked', false);
                            $input.val(total_);
                        }
                    } else if (totalTmp < total_) {
                        $this_.closest('tr').find('input[type=text]').val(tmp_)
                    }
                    total = totalTmp;
                });
                $('.modal input[type=checkbox]').not(":checked").each(function (index, item) {
                    $(this).closest('tr').find('input[type=text]').val(0);
                });
                initTips(calculate(), total);
                return total;
            }

            /**
             * 初始化选择
             */
            function initSelectedBath(orderId, batches) {// 批号和订单匹配
                var $order = $('.class-' + orderId).data('json'); // debugger // delete
                var html_ = '', selectedOrder = {}, selectedOrderArray = [];
                $('.send-order').find('tr').each(function (idex, item) {
                    var $json = $(this).data('json');
                    if ($json) {
                        $json.canSendNum = parseFloat($(this).find('[name=orderNumbers]').val()) || 0;
                        $json.needSend = $json.canSendNum;// 订单需发货
                        selectedOrder[$json.id] = $json;
                        selectedOrderArray.push($json);
                    }
                });
                var i_ = 0;

                function render(item, isCurrent, send) {
                    return ejs.render($('#template-order-selected-batch').html(), {
                        order: item,
                        item: send,
                        isCurrent: isCurrent
                    })
                }

                selectedOrderArray = selectedOrderArray.map(function (item) {
                    if (!item.sortOrder) {
                        item.sortOrder = 0;
                    }
                    return item;
                })
                _.sortBy(selectedOrderArray, 'sortOrder').map(function (item, index) {
                    // item = selectedOrder[item];
                    var current = batches[i_];
                    debugger;
                    if (!current) {
                        html_ += render(item, item.id == _search.id, {
                            batchNum: '',
                            numberReceive: 0,
                            number: 0,
                            numberSending: 0,
                            id: '',
                            quality: '',
                            send: 0
                        });
                        return;
                    }
                    if (item.needSend > current.send) {
                        item.send = current.send;
                        i_++;
                        item.needSend = floatTool.subtract(item.needSend, current.send);//扣减批号匹配数量后剩余可发货数量
                        html_ += render(item, item.id == _search.id, $.extend({}, current, {send: item.send}));
                        if(i_>=batches.length){ //
                            return ;
                        }
                        var i1 = findNextBatch(batches, i_, item.needSend);
                        for (var j = i_; j < i1; j++) {
                            var batchItem = batches[j];
                            if (item.needSend == batchItem.send) {
                                item.send = batchItem.send;
                                html_ += render(item, item.id == _search.id, $.extend({}, batchItem, {send: item.send}));
                            } else if (item.needSend < batchItem.send) {
                                item.send = item.needSend;
                                html_ += render(item, item.id == _search.id, $.extend({}, batchItem, {send: item.send}));
                            } else if (item.needSend > batchItem.send) {
                                item.send = batchItem.send;
                                item.needSend = floatTool.subtract(item.needSend, batchItem.send)
                                html_ += render(item, item.id == _search.id, $.extend({}, batchItem, {send: batchItem.send}));
                            }
                        }
                        i_ = i1;
                        var tmp = batches[i1];
                        if (tmp.send > item.needSend) {
                            item.send = item.needSend;
                            tmp.send = floatTool.subtract(tmp.send, item.needSend);
                            html_ += render(item, item.id == _search.id, $.extend({}, tmp, {send: item.send}));
                        } else if (tmp.send <= item.needSend) {
                            item.send = tmp.send;
                            i_++;
                            html_ += render(item, item.id == _search.id, $.extend({}, tmp, {send: item.send}));
                        }

                    } else if (item.needSend == current.send) {
                        item.send = current.send;
                        i_++;
                        html_ += render(item, item.id == _search.id, $.extend({}, current, {send: item.send}));

                    } else if (item.needSend < current.send) {
                        item.send = item.needSend;
                        current.send = floatTool.subtract(current.send, item.needSend);
                        html_ += render(item, item.id == _search.id, $.extend({}, current, {send: item.send}));
                    }
                    return;
                });
                $('.send-order').find('tr').each(function (index, item) {
                    if ($(item).index() != 0 && $(item).index() != ($('.send-order').find('tr').length - 1)) {
                        $(item).remove();
                    }
                });
                $(html_).insertAfter($('.send-order').find('tr:nth-child(1)'));// 插入第一个订单后面
                /***
                 * 查询下一个能满足条件的批号
                 * @param batches 所选批号
                 * @param startIndex 开始索引
                 * @param remainTotal 剩余数量
                 */
                function findNextBatch(batches, startIndex, remainTotal) {
                    if(startIndex>=batches.length)throw new Error('超出范围')
                    var total = 0, i = 0;
                    for (i = startIndex; i < batches.length;) {
                        var item = batches[i];
                        var totalTmp = floatTool.add(total, item.send);
                        if (totalTmp < remainTotal) {
                            total = totalTmp;
                            i++;
                        } else if (totalTmp > remainTotal) {
                            break;
                        } else {
                            break;
                        }
                    }
                    if (i >= batches.length) {
                        return batches.length - 1;
                    }
                    return i;
                }

                initSendNumberThisTime();
                focusEvent();
                deleteEvent();
            }

            function getBatchNumber() {
                var $id = $(this).data('id');
                var url = config.getPurchaseOrderBill + res.data.goodsId;
                if ($('[name=type]').val() == 0 || $('[name=type]').val() == 2) {
                    url += '&checkStatus=1';
                } else {
                    url += '&checkStatus=1&numberReceive=1'
                }
                function getByStore(storeId) {
                    var deffer = $.Deferred();
                    $.get(url + '&storeId=' + storeId)
                        .then(function (res) {
                            deffer.resolve(res);
                        });
                    return deffer.promise();
                }

                /**
                 * 打开选择批号弹框后的初始化
                 */
                function initEventWhenSelectBatch() {
                    $('.modal-body input[type=checkbox]').change(function (index, item) {
                        if ($(this).is(':checked')) {
                            if ($('.modal input[type=checkbox]:checked').length == 1) {
                                $(this).data('order', 1);
                            } else {
                                var t = $('.modal input[type=checkbox]:checked').map(function (index, item) {
                                    if ($(item).data('order') == 'undefined' || $(item).data('order') == undefined) { // 当前元素
                                        return 0;
                                    }
                                    return parseInt($(item).data('order'));
                                });
                                $(this).data("order", _.max(t) + 1);
                            }
                        }
                        getSelectedBatch($id, this); //     //

                    });
                    selected_ = {};
                    getSelectedBatch($id); // 选择批号
                    onInput($('.modal input[type=text]'), function () {
                        var max = getCanSend($(this).closest('tr').find('[type=checkbox]').data('json'));
                        var inputVal = $(this).val();
                        if (parseFloat(inputVal) == NaN) {
                            inputVal = 0
                        } else {
                            inputVal = parseFloat(inputVal);
                        }
                        if (inputVal > max) {
                            $(this).val(max);
                        }

                    });
                    // $('.modal input[type=checkbox] ').closest('tr').find('[type=text]').not(":checked").each(function (index, item) {
                    //     $(this).closest('tr').find('input[type=text]').val(0);
                    // });
                }

                $.when(parent.window.getDataByUrl(config.query_store, 'stores'),
                    window.parent.getDataByUrl(url, 'getPurchaseOrderBill' + Math.random()))
                    .then(function (stores, res) {
                        _alert({
                            width: '98%',
                            title: '选择批号:',
                            body: ejs.render(strSelectHtml, {purchase: res, selected: selected, stores: stores}),
                            show: function () {
                                initTips(calculate(), 0);
                                $('.modal-body').addClass('min-height250');
                            },
                            shown: function () {
                                initEventWhenSelectBatch();
                                $('#store').selectpicker({
                                    liveSearch: true
                                })
                                    .change(function (e) {
                                        getByStore($(this).val())
                                            .then(function (res) {
                                                $('.modal-content table').replaceWith(ejs.render($('#select-batch').html(), {
                                                    purchase: res.list,
                                                    selected: selected
                                                }));
                                                initEventWhenSelectBatch();
                                            });
                                    })
                            },
                            okHide: function (e) {
                                selected = {};
                                var store = {};
                                $('.modal input[type=checkbox]:checked').each(function (index, item) {
                                    var $json = $(this).data('json');
                                    $json.send = parseFloat($(this).closest('tr').find('input.form-inline').val());
                                    $json.sortOrder = $(this).data('order');// 选择顺序
                                    store[$json.storeId] = $json;
                                    selected[$json.id] = $json;
                                });
                                if (!Object.keys(store).length) {
                                    fnFail("请选择批号！");
                                    return false;
                                }
                                if (Object.keys(store).length > 1) {
                                    fnFail("请选择同一个发货仓库");
                                    return false;
                                }
                                getStore(Object.keys(store)[0]);
                                var stores = _.values(store);
                                $('[name=storeName]').val(stores[0].storeName);
                                $('[name=storeId]').val(stores[0].storeId);
                                initSelectedBath($id, _.sortBy(_.values(selected), 'sortOrder'));
                                return true;
                            },
                            hasfoot: true,
                        });
                    })
                    .fail(function (e) {
                        fnFail(e);
                    })
            }

            function getStore(storeId) {
                if ($('input[name=type]').val() == 0) {
                    $.get('/store/detail/' + storeId, function (res) {
                        if (res.code == 200) {
                            if (res.data.showDriver == "1") {
                                if ($('.type-order .driver').length == 0) {
                                    var store = '<tr class="driver"> \
                            <td class="td-label">司机姓名：</td> \
                            <td class="td-label-value" style="padding: 1px 8px;"> \
                                <input name="driver" class="form-control"/></td> \
                                <td class="td-label">身份证号：</td> \
                            <td class="td-label-value" style="padding: 1px 8px;">\
                                <input name="driverPhone" class="form-control"/>\
                            </td><td class="td-label"></td> \
                            <td class="td-label-value" style="padding: 1px 8px;"></td></tr>';
                                    $(store).insertAfter($('.type-order tr'))
                                }
                            }
                        }
                    })
                }
            }
            var page = 1,loadedOrder = [];
            $('.send-order').find('tr:nth-child(3)').length
            // 选择合并发货订单
            $combine.click(function () {
                var item = $(this).data('json');
                if(loadedOrder.length){
                    alert_();
                    return;
                }
                $.get(config.getRelatedOrder + '?status=0&unitCode=' + item.unitCode + '&goodsId=' + item.goodsId + '&checkStatus=1', function (xhr) {
                    if (xhr.code == 200) {
                        loadedOrder = xhr.list;
                        alert_();
                    }
                });


                function alert_() {
                    var $modal = _alert({
                        width: '96%',
                        title: '合并发货',
                        body: ejs.render(strCombineHtml, {orders: loadedOrder, selected: orders}),
                        shown: function () { //订单按选择顺序进行排序，
                            // validate($modal);
                            var loading = false;
                            function loadMore() {
                                // onClick($('.modal tbody tr'),function (e) {
                                //     var $THIS = $(this).find('input[type=checkbox]');
                                //     $(this).find('input[type=checkbox]').attr('checked',!$THIS.is(':checked')).prop('checked',!$THIS.is(':checked'));
                                // // });
                                onClick($('.modal input[type=checkbox]'), function (e) {
                                    //e.stopPropagation();
                                    //e.preventDefault();
                                    if ($(this).is(':checked')) {
                                        if ($('.modal input[type=checkbox]:checked').length == 1) {
                                            return $(this).data('order', 1);
                                        }
                                        var t = $('.modal input[type=checkbox]:checked').map(function (index, item) {
                                            if ($(item).data('order') == 'undefined' || $(item).data('order') == undefined) { // 当前元素
                                                return 0;
                                            }
                                            //console.log(parseInt($(item).data('order')));
                                            return parseInt($(item).data('order'));
                                        });
                                        $(this).data("order", _.max(t) + 1);
                                    }
                                });
                                onClick($('.loading-more'),function () {
                                    if(!loading){
                                        loading   = true;
                                    }else {
                                        return fnFail("加载中....");
                                    }
                                    page++;
                                    $.get(config.getRelatedOrder + '?status=0&unitCode=' + item.unitCode + '&goodsId=' + item.goodsId + '&checkStatus=1&page='+page, function (xhr) {
                                        loading = false;
                                        loadedOrder = loadedOrder.concat(xhr.list);
                                        $('.modal-body >div').replaceWith(ejs.render(strCombineHtml, {orders: loadedOrder, selected: orders}));
                                        loadMore();
                                    });
                                })
                            }
                            loadMore();
                        },
                        okHide: function () {
                            var selectedOrder = [];
                            $('.modal input[type=checkbox]:checked').each(function () {
                                var $json = $(this).data('json');
                                $json.sortOrder = parseInt($(this).data('order'));
                                selectedOrder.push($json)
                            });
                            _.sortBy(selectedOrder, 'sortOrder').map(function ($json) {
                                orders[$json.id] = $json;
                                var $tr = $(ejs.render(strOrderItemHtml, $json));
                                $json.sendNum = $json.canSendNum;
                                $tr.data('json', $json);
                                $tr.insertBefore('.send-order tr:last-child');
                                focusEvent(); //
                                initNumberPage($json);
                                initEvent();
                                deleteEvent();
                            });
                            onInput($('[name=orderNumbers]'), function () {
                                if (parseFloat($(this).val()) > parseFloat($(this).attr('max'))) {
                                    $(this).val($(this).attr('max'));
                                }
                                initSendNumberThisTime();
                                initBatchNum();
                            });

                            return true;
                        },
                        hasfoot: true,
                    });
                }
            });
            function focusEvent() {
                $('.select-batch').unbind('focus').focus(getBatchNumber);
            }
        } else {
            fnFail(res.error);
        }
    });
    function deleteEvent() {
        $('.send-order .btn-delete').unbind('click').click(function () {
            $(this).closest('tr').remove();
            if ($(this).data('id') && orders[$(this).data('id')]) {
                initNumberPage({id: $(this).data('id')}, true);
            }
        });
    }

    var submiting = false;
    $('#form-send').submit(function (e) {
        e.stopPropagation();
        e.preventDefault();
        var $formStr = $('#form-send').serialize();
        var form = parseSearch($formStr);

        var hasUnpay = false;
        if (submiting) {
            return;
        } else {
            submiting = true;
        }
        if ($('[name=driver]').length) {
            if (!form.driver) {
                submiting = false;
                return fnFail('请填司机姓名')
            } else {
                form.driver = form.driver.replace('+', '')
            }
        }
        if (!form.carId) {
            submiting = false;
            return fnFail('请填车号或转货公司')
        }
        if (!form.expireTime) {
            submiting = false;
            return fnFail('请填提单有效期或免费仓储期')
        }
        if ($('[name=driver]').length) {
            if (!form.driver) {
                submiting = false;
                return fnFail('请填司机姓名')
            }
        }
        if ($('[name=driverPhone]').length) {
            if (!form.driverPhone) {
                submiting = false;
                return fnFail('请填司机身份证号');
            }
        }
        var quality = {};
        // if (form.quality) {
        //     form.quality.split(',').map(function (item) {
        //         quality[item] = item;
        //     });
        // if (Object.keys(quality).length != 1) {
        //     return alert("发货只能选择同一个品质规格的货物!");
        // }
        // }
        form.numberThisTime = 0;
        if (form.orderNumbers) {
            form.orderNumbers.split(',').map(function (item) {
                form.numberThisTime = floatTool.add(parseFloat(item), form.numberThisTime);
            })
        } else {
            submiting = false;
            return fnFail("请选择批号!")
        }
        // if (form.quality) {
        //     form.quality = $('[name=quality]').val();
        // }
        form.carId = form.carId.replace('+', '');
        // var total_ = 0;
        // form.orderNumbers.split(',').each(function (item) {
        //     total_ = floatTool.add(total_, parseFloat(item));
        // })
        var total_ = $('.send-total').html();
        var can_total_ = $('.can-send-total').html();
        if (parseFloat(total_) > 0 && parseFloat(total_) <= parseFloat(can_total_)) {

        } else {
            return fnFail("发货数量合计不能为0或本次发货数量必须小于等于可发货数量");
        }
        $.post(config.create_labing_bill, form, function (xhr, data) {
            if (xhr.code == 200) {
                alert('发货成功!');
                submiting = false;
                window.location = './index.html';
            } else {
                if (hasUnpay && xhr.error.indexOf('无权操作') > -1) {
                    fnFail("货款不足，请补足货款再操作!")
                } else {
                    fnFail(xhr.error)
                }
            }
        });
        return false;
    });
    // 发货提交
    onClick($submitSend, function () {

    });

    $("[name=expireTime]").datepicker($.extend({}, dateSetting, {}));


});